1 /* 2 * Copyright (C) 2007 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.collect; 18 19 import com.google.common.annotations.GwtCompatible; 20 21 import java.util.HashMap; 22 23 /** 24 * Multiset implementation backed by a {@link HashMap}. 25 * 26 * @author Kevin Bourrillion 27 * @author Jared Levy 28 * @since 2.0 (imported from Google Collections Library) 29 */ 30 @GwtCompatible(serializable = true, emulated = true) 31 public final class HashMultiset<E> extends AbstractMapBasedMultiset<E> { 32 33 /** 34 * Creates a new, empty {@code HashMultiset} using the default initial 35 * capacity. 36 */ 37 public static <E> HashMultiset<E> create() { 38 return new HashMultiset<E>(); 39 } 40 41 /** 42 * Creates a new, empty {@code HashMultiset} with the specified expected 43 * number of distinct elements. 44 * 45 * @param distinctElements the expected number of distinct elements 46 * @throws IllegalArgumentException if {@code distinctElements} is negative 47 */ 48 public static <E> HashMultiset<E> create(int distinctElements) { 49 return new HashMultiset<E>(distinctElements); 50 } 51 52 /** 53 * Creates a new {@code HashMultiset} containing the specified elements. 54 * 55 * <p>This implementation is highly efficient when {@code elements} is itself 56 * a {@link Multiset}. 57 * 58 * @param elements the elements that the multiset should contain 59 */ 60 public static <E> HashMultiset<E> create(Iterable<? extends E> elements) { 61 HashMultiset<E> multiset = 62 create(Multisets.inferDistinctElements(elements)); 63 Iterables.addAll(multiset, elements); 64 return multiset; 65 } 66 67 private HashMultiset() { 68 super(new HashMap<E, Count>()); 69 } 70 71 private HashMultiset(int distinctElements) { 72 super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); 73 } 74 } 75